<template>
	<view class="zgj-voice uni-border" @click="togglePlay" v-if="info">
		<image :src="voiceImg"></image>
		<text>{{info.time}}s</text>
	</view>
</template>

<script>
	export default {
		name:'ZgjVoice',
		props:{
			info:{
				type:Object,
				default(){
					return null
				}
			}
		},
		watch:{
			info(newVal,oldVal){
				if(newVal===null){
					if(this.audioCtx){
						this.audioCtx.stop()
					}
				}
				else{
					if(!this.audioCtx){
						this.audioCtx = this.createAuidoCtx()
					}
					this.audioCtx.src = newVal.url
				}
			}
		},
		data(){
			return {
				playing:false,
				audioCtx:null
			}
		},
		computed:{
			voiceImg(){
				return this.playing ? 'https://env-00jxhjo1f70q.normal.cloudstatic.cn/1742721079066_0.gif?expire_at=1742721680&er_sign=9ad17cad33c9e11736a3044425887b21' : 'https://env-00jxhjo1f70q.normal.cloudstatic.cn/1742721125140_0.png?expire_at=1742721726&er_sign=6c55f0f325d1be5c515e35d7b8190b5c'
			}
		},
		methods:{
			togglePlay(){
				if(!this.audioCtx) {
					this.audioCtx = this.createAuidoCtx()
					this.audioCtx.src = this.info.url
				}
				console.log(this.info,this.audioCtx,this.playing)
				if(this.playing){
					this.audioCtx.stop()
				}
				else{
					this.audioCtx.play()
				}
			},
			createAuidoCtx(){
				var audioCtx = uni.createInnerAudioContext()
				audioCtx.autoplay =false
				audioCtx.onPlay(()=>{
					this.playing = true
				})
				audioCtx.onStop(()=>{
					this.playing = false
				})
				audioCtx.onPause(()=>{
					this.playing = false
				})
				audioCtx.onEnded(()=>{
					this.playing = false
				})
				audioCtx.onError((err)=>{
					console.log("audio error:",err)
					this.playing = false
				})
				return audioCtx
			}
		}
	}
</script>

<style lang="scss" scoped>
	.zgj-voice{
		height: 60rpx;
		width: 200rpx;
		margin-top: 6px;
		background-color: #F7FFFC;
		border-radius: 30rpx;
		display: flex;
		flex-direction: row;
		align-items: center;
		image{
			margin-left: 10rpx;
			width: 44rpx;
			height: 44rpx;
		}
		text{
			margin-left: 10px;
		}
	}
</style>